<template>
	<div class="component-backTop" :style="{ display: isShow ? 'block' : 'none' }" @click="iconClick">
		<div class="btn"><img :src="icon" alt="" /></div>
	</div>
</template>

<script setup>
import { ref, nextTick, onBeforeUpdate } from 'vue';

const componetName = '回到顶部';
const icon = require('@mall/assets/img/arrows-up-white@3x.png');
const isShow = ref(false);

const handleScroll = debounce(e => {
	let y = document.documentElement.scrollTop || document.body.scrollTop;
	let scrollHeight = document.body.scrollHeight; //滚动条最大高度
	let pageHeight = getViewportSize().height; //屏幕高度
	isShow.value = false;
	if (y >= pageHeight) {
		isShow.value = true;
	}
}, 100);

const iconClick = throttle(() => {
	smoothScrollTop(5);
});

nextTick(() => {
	window.addEventListener('scroll', handleScroll, true);
});

onBeforeUpdate(() => {
	window.removeEventListener('scroll', handleScroll);
});

//获取屏幕宽高
function getViewportSize() {
	return {
		width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
		height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
	};
}
// 防抖
function debounce(func, delay = 350) {
	let timeout = null;
	return function() {
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			func.apply(this, arguments);
		}, delay);
	};
}
// 节流
function throttle(fn, wait = 350) {
	var timer = null;
	return function() {
		var context = this;
		var args = arguments;
		if (!timer) {
			timer = setTimeout(function() {
				fn.apply(context, args);
				timer = null;
			}, wait);
		}
	};
}
//返回顶部
function smoothScrollTop(n = 5) {
	(function smoothscroll() {
		let currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
		if (currentScroll > 0) {
			window.requestAnimationFrame(smoothscroll);
			window.scrollTo(0, currentScroll - currentScroll / n);
		}
	})();
}
</script>

<style lang="scss" scoped>
@import '@mall/assets/css/common';
.component-backTop {
	position: fixed;
	bottom: rem(260);
	right: rem(20);
	z-index: 999;
	border-radius: 50%;
	overflow: hidden;

	.btn {
		width: rem(90);
		height: rem(90);
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		background: $tc;
		img {
			width: 75%;
		}
	}
}
</style>
